package com.eco.fishway.netty;


import com.eco.fishway.service.LightService;
import com.eco.fishway.util.ApplicationContextProvider;
import com.eco.fishway.util.NettyCtxMap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

/**
 * @author: xulinyu
 * Created at: 2024/8/7 16:39
 */
@Slf4j
public class KndInHexHandler extends ChannelInboundHandlerAdapter {

    private final KndInNettyClient nettyClient;
    private final LightService lightService;
    private static final String ON_COMMAND_GRATING = "00 00 00 00 00 06 FF 05 00 64 FF 00";

    public KndInHexHandler() {
        this.nettyClient = ApplicationContextProvider.getBean(KndInNettyClient.class);
        this.lightService = ApplicationContextProvider.getBean(LightService.class);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleState state = ((IdleStateEvent) evt).state();
            if (state == IdleState.WRITER_IDLE) {
                String msg = new String(ON_COMMAND_GRATING.getBytes(), "utf-8");
                ctx.writeAndFlush(msg);
                return;
            }
            return;
        }
        super.userEventTriggered(ctx, evt);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("knd-tcp进口有新连接");
        NettyCtxMap.add(nettyClient.getServerId(), ctx);
        this.lightService.sendCommand(nettyClient.getServerId(), ON_COMMAND_GRATING);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        String host = this.nettyClient.getHost();
        int port = this.nettyClient.getPort();
        log.error("与knd-tcp进口服务端" + host + ":" + port + "连接断开!");
        ctx.close();
        ctx.deregister();
        ctx.pipeline().remove(this);
        this.nettyClient.kndReconnect();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg != null) {
            try {
                String kndMsg = msg.toString();
                log.info("knd-tcp进口服务端返回的消息：{}", kndMsg);
            } catch (Exception e) {
                log.error(e.toString());
            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("knd-tcp进口连接异常");
        ctx.close();
    }
}
